<template>
  <section class="todoapp">
    <TodolistHeader @addList="newList"></TodolistHeader>
    <TodolistBody
      :list="renderList"
      @changeFlag="changeFlag"
      @delList="delList"
      @allselect="allselect"
    ></TodolistBody>
    <TodolistFooter
      :sum="sum"
      :showbtn="showbtn"
      @clearBtn="clearBtn"
      :type="type"
      @selectList="selectList"
    ></TodolistFooter>
  </section>
</template>

<script>
import TodolistHeader from './components/TodolistHeader.vue'
import TodolistBody from './components/TodolistBody.vue'
import TodolistFooter from './components/TodolistFooter.vue'

export default {
  components: { TodolistHeader, TodolistBody, TodolistFooter },
  data() {
    return {
      type: 'all',
      list: JSON.parse(localStorage.getItem('listSave')) || [
        { id: 1, flag: true, value: '读万卷书' },
        { id: 2, flag: false, value: '行万里路' },
      ],
    }
  },
  methods: {
    // 添加事件
    newList(value) {
      // 合并数组
      this.list = [
        ...this.list,
        {
          // id的值为字符串或者数字
          id: +new Date(),
          flag: false,
          value,
        },
      ]
    },
    // 修改事件完成状态
    changeFlag(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag = flag
      })
    },
    // 删除事件
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    // 删除已经完成的事件
    clearBtn() {
      this.list = this.list.filter((item) => !item.flag)
    },
    selectList(type) {
      this.type = type
    },
    // 全选
    allselect(flag) {
      this.list.forEach((item) => (item.flag = flag))
    },
  },
  // 记事总数--计算属性
  computed: {
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    // 清除已完成 显示
    showbtn() {
      // arr.some 默认值为false ,如果有true，返回结果就为true
      return this.list.some((item) => item.flag)
    },
    // 根据不同类型的type筛选类型去展示不同的数据
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(newVal) {
        return localStorage.setItem('listSave', JSON.stringify(newVal))
      },
    },
  },
}
</script>

<style></style>
